//
//  BaseWebViewController.m
//  PandaTakeaway
//
//  Created by smufs on 2017/6/27.
//  Copyright © 2017年 李冰. All rights reserved.
//

#import "BaseWebViewController.h"

@interface BaseWebViewController ()

@property (nonatomic, strong) CALayer *progresslayer;

@property (nonatomic, strong) UILabel *titleLabel;

@end

@implementation BaseWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.automaticallyAdjustsScrollViewInsets = NO;
    [self _setupUI];
    
}

- (void) _setupUI {
    
    [self initWithProgressView];
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
    _titleLabel.font = lbFont(14);
    _titleLabel.textColor = kWhiteColor;
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = _titleLabel;

    // back btn
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"shangjiaxinxi_fanhui"] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 20, 30);
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}

- (void) _setupSource {

}

- (void)createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration {

    if (_webView)
    {
        [_webView removeFromSuperview];
        [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
        [self.webView removeObserver:self forKeyPath:@"title" context:nil];
        _webView = nil;
    }
    
    if (!configuration)
    {
        configuration = [[WKWebViewConfiguration alloc] init];
        
//        configuration.userContentController = [WKUserContentController new];
//        // 自适应屏幕宽度js
//        NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
//        WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//        [configuration.userContentController addUserScript:wkUserScript];
    }
    
    _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    [self _addObservers];
    [self.view addSubview:_webView];
    [self.view addSubview:[self.view viewWithTag:2020]];
}

- (void)loadWithURL:(NSURL *)url {
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}

- (void)loadHTMLString:(NSString *)html {

    [self.webView loadHTMLString:html baseURL:nil];
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)_addObservers{
    //添加观察者,观察wkwebview的estimatedProgress属性
    [self.webView addObserver:self
                   forKeyPath:@"estimatedProgress"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"title"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
};

- (void)dealloc {

    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title" context:nil];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"title"])
    {
        self.titleLabel.text = self.webView.title;
    }
    else if ([keyPath isEqualToString:@"estimatedProgress"])
    {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        
        self.progresslayer.opacity = 1;
        
        //不要让进度条倒着走...有时候goback会出现这种情况
        if ([change[@"new"] floatValue] < [change[@"old"] floatValue])
        {
            return;
        }
        self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[@"new"] floatValue], 3);
        if ([change[@"new"] floatValue] == 1) {
            
            WKWebView *web = object;
            
            [web evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id Result, NSError * error) {
                
                
            }];
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progresslayer.opacity = 0;
            });
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progresslayer.frame = CGRectMake(0, 0, 0, 3);
            });
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)back{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)initWithProgressView{
    UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.frame), 3)];
    [self.view addSubview:progress];
    progress.tag = 2020;
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 0, 0, 2);
    layer.backgroundColor = [UIColor orangeColor].CGColor;
    [progress.layer addSublayer:layer];
    self.progresslayer = layer;
}

@end
